package com.wanpinghui.supplier.user.product;

import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseWebActivity;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.oauth.LoginActivity;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.UrlConstants;
import com.wanpinghui.wphlibrary.model.base.FileUploadManager;
import com.wanpinghui.wphlibrary.model.base.bean.ImageBean;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.product.bean.ProductMgrImageBean;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.wanpinghui.wphlibrary.photovideo.view.ClipActivity;
import com.wanpinghui.wphlibrary.webapp.BaseJsInvokeListener;
import com.wanpinghui.wphlibrary.webapp.JSMethod;
import com.wanpinghui.wphlibrary.webapp.WPHWebView;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.PhotoPickManager;
import retrofit.callback.YRequestCallback;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/***
 * 功能描述:货源管理
 * 作者:qiujialiu
 * 时间:2018/1/15
 ***/
@ContentView(R.layout.layout_activity_product_manager)
public class ProductManagerActivity extends BaseWebActivity {
    public static final int REQUEST_SELECT_PHOTO = 101;
    private static final int CLIP_PHOTO = 102;
    @ViewInject(R.id.web_view)
    private WPHWebView wphWebView;
    @ViewInject(R.id.rl_loading)
    private RelativeLayout layoutLoading;
    @ViewInject(R.id.tv_error)
    private TextView textViewError;

    private ArrayList<UploadFileBean> photoList;
    private int fileSize;//要上传的图片的size
    private int finishSize;//上传完成的图片的size
    private List<ProductMgrImageBean> imgList;

    private String url = UrlConstants.WebAppURL + "/my_pro_center.html";


    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        wphWebView.addJsMethod(new JSMethod(UrlConstants.URL, new BaseJsInvokeListener() {
            @Override
            public void onSelectPhoto(List<ProductMgrImageBean> list) {
                imgList = list;
                PhotoPickManager.selectPic(ProductManagerActivity.this, REQUEST_SELECT_PHOTO, 9, false, list == null ? 0 : list.size());
            }

            @Override
            public void onUploadPhoto(List<ProductMgrImageBean> list) {
                if (list != null && list.size() > 0) {
                    fileSize = list.size();
                    imgList = list;
                    if (list != null && list.size() > 0) {
                        //LoadingDialog.Build(ProductManagerActivity.this).setContent("上传中...").show();
                        for (ProductMgrImageBean bean : list) {
                            if (TextUtil.isEmpty(bean.getUrl())) {
                                uploadImage(bean);
                            }
                        }
                    }
                }
            }

            @Override
            public void goBack() {
                finish();
            }

            @Override
            public void tokenInvalid() {
                NimManager.getInstance().logout();
                startActivity(new Intent(ProductManagerActivity.this, LoginActivity.class));
                finish();
            }
        }));
    }

    @Override
    public void bindEvents() {
        textViewError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wphWebView.loadUrl(url);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        if (LoginUtil.loginFilter(this)) {
            String token = WPHSdk.getService(OAuthService.class).getToken();
            url = url + "?token=" + token;
        }
        layoutLoading.setVisibility(View.VISIBLE);
        textViewError.setVisibility(View.GONE);
        wphWebView.loadUrl(url);
    }

    @Override
    protected void onLoadError() {
        layoutLoading.setVisibility(View.GONE);
        textViewError.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onLoadSuccess() {
        layoutLoading.setVisibility(View.GONE);
        textViewError.setVisibility(View.GONE);
    }

    @Override
    protected void onLoadStart() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_PHOTO) {
            if (data != null) {
                Intent intent = new Intent(ProductManagerActivity.this, ClipActivity.class);
                intent.putExtra("data", PhotoPickManager.getPhoto(data));
                //   intent.putExtra("scale",2);
                startActivityForResult(intent, CLIP_PHOTO);
            }
        } else if (requestCode == CLIP_PHOTO) {
            if (data != null) {
                photoList = data.getParcelableArrayListExtra("result");
                Observable.from(photoList)
                        .map(new Func1<UploadFileBean, ProductMgrImageBean>() {
                            @Override
                            public ProductMgrImageBean call(UploadFileBean uploadFileBean) {
                                ProductMgrImageBean imageBean = new ProductMgrImageBean();
                                imageBean.setBase64(FileUploadManager.bitmapToString2(uploadFileBean.getPath()));
                                imageBean.setPath(uploadFileBean.getPath());
                                return imageBean;
                            }
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<ProductMgrImageBean>() {
                            @Override
                            public void onCompleted() {
                                wphWebView.setPhotos(imgList);
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(ProductMgrImageBean s) {
                                if (imgList == null) {
                                    imgList = new ArrayList<>();
                                }
                                imgList.add(s);
                            }
                        });
            }
        }
    }


    private void uploadImage(final ProductMgrImageBean bean) {
        FileUploadManager.uploadProductImage(bean.getPath(), new YRequestCallback<ImageBean>() {
            @Override
            public void onSuccess(ImageBean var1) {
                finishSize++;
                bean.setUrl(var1.getUrl());
                setUploadImages();
            }

            @Override
            public void onFailed(int var1, String message) {
                finishSize++;
                setUploadImages();
            }

            @Override
            public void onException(Throwable var1) {
                finishSize++;
                setUploadImages();
            }
        });
    }

    private void setUploadImages() {
        if (finishSize == fileSize) {
            //LoadingDialog.dismissDialog();
            wphWebView.setUploadPhotos(imgList);
            finishSize = 0;
        }
    }

    @Override
    protected WPHWebView getWebView() {
        return wphWebView;
    }

    @Override
    public void onBackPressed() {
      if(wphWebView!=null){
         wphWebView.goWebBack();
      }else {
          super.onBackPressed();
      }
    }
}
